package com.sms.web.system.service;

import java.util.ArrayList;
import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sms.common.persistence.DynamicSpecifications;
import com.sms.common.persistence.Operator;
import com.sms.common.persistence.SearchFilter;
import com.sms.web.system.dao.SysMenuDao;
import com.sms.web.system.dao.SysRoleMenuDao;
import com.sms.web.system.entity.SysMenu;

/**
 * @desc 
 * @author wjw
 * @time 2017年11月16日下午3:34:16
 */
@Service
@Transactional
public class SysMenuService {
    
    protected Logger logger = LoggerFactory.getLogger(getClass());
    
    @Autowired
    private SysMenuDao menuDao;
    @Autowired
    private SysRoleMenuDao rmDao;
    
    /** 保存菜单 */
    public SysMenu saveMenu(SysMenu entity) {
        return menuDao.save(entity);
    }
    
    /** 删除菜单 */
    public void delete(String id) {
    	//1.删除角色菜单
    	rmDao.deleteInBatch(rmDao.findByMenuId(id));
    	//2.删除菜单
    	rmDao.deleteById(id);
    }
    
    /** 查询菜单 */
    public SysMenu findById(String id) {
        return menuDao.getOne(id);
    }
    
    /**
     * 分页查询菜单
     * @param serchkey
     * @param pageNumber
     * @param pageSize
     * @param sort 排序条件
     * @return
     */
    @Transactional(readOnly = true)
    public Page<SysMenu> findByKeyword(String serchkey, int pageNumber, int pageSize) {
    	//1.定义jpa分页对象
    	Sort sort = new Sort(Direction.DESC, "id");
        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize, sort);
        //2.构建动态查询条件
        Collection<SearchFilter> filters = new ArrayList<>();
        filters.add(new SearchFilter("menuName", Operator.LIKE , serchkey));//模糊匹配角色名
        filters.add(new SearchFilter("delFlag", Operator.EQ , "0"));//查询未删除数据
        Specification<SysMenu> spec = DynamicSpecifications.bySearchFilter(filters, SysMenu.class);
        return menuDao.findAll(spec, pageRequest);
    }
}
